/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.worker.ui.async.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.ourgrid.common.ui.AbstractInputFieldsPanel;
import org.ourgrid.common.ui.OurGridUIModel;
import org.ourgrid.common.util.CommonUtils;
import org.ourgrid.peer.ui.async.gui.OurGridFileChooser;
import org.ourgrid.worker.WorkerConfiguration;
import org.ourgrid.worker.ui.async.client.WorkerAsyncInitializer;
import org.ourgrid.worker.ui.async.model.WorkerAsyncUIModel;

import br.edu.ufcg.lsd.commune.network.signature.SignatureProperties;

/**
 * It represents a panel where it is possible to define the basic
 * worker settings, like: playpen root and idleness root.
 * @author Diego
 */
public class WorkerBasicSettingsPanel extends AbstractInputFieldsPanel {

	/** Creates new form WorkerBasicSettingsPanel */
    public WorkerBasicSettingsPanel(OurGridUIModel model) {
    	super(model);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    protected void initComponents() {

        rootPanel = new javax.swing.JPanel();
        playpenRootLabel = new javax.swing.JLabel();
        idlenessPanel = new javax.swing.JPanel();
        playpenRootField = new javax.swing.JTextField();
        storageRootLabel = new javax.swing.JLabel();
        storageRootField = new javax.swing.JTextField();
        idlenessTimeoutLabel = new javax.swing.JLabel();
        idlenessTimeoutSpinner = new javax.swing.JSpinner();
        keySettingsPanel = new javax.swing.JPanel();
        enableIdlenessCheckBox = new javax.swing.JCheckBox();
        peerPublicKeyLabel = new javax.swing.JLabel();
        loadButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        peerPubKeyTextArea = new javax.swing.JTextArea();


        rootPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Root Settings"));

        playpenRootLabel.setText("Playpen Root:");


        storageRootLabel.setText("Storage Root:");
        
        org.jdesktop.layout.GroupLayout localhostPanelLayout = new org.jdesktop.layout.GroupLayout(rootPanel);
        rootPanel.setLayout(localhostPanelLayout);
        localhostPanelLayout.setHorizontalGroup(
            localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(localhostPanelLayout.createSequentialGroup()
                .add(localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                		.add(playpenRootLabel)
                		.add(storageRootLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                		.add(playpenRootField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                		.add(storageRootField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 200, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
     )   );
        localhostPanelLayout.setVerticalGroup(
            localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(localhostPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                		.add(playpenRootLabel)
                		.add(playpenRootField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                    .add(localhostPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                		.add(storageRootLabel)
                		.add(storageRootField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                	.addContainerGap(20, Short.MAX_VALUE)
        ) );

        idlenessPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Idleness Settings"));

        
        enableIdlenessCheckBox.setText("Enable Idleness Detector:");

        idlenessTimeoutLabel.setText("Idleness Timeout:");

        org.jdesktop.layout.GroupLayout lanPanelLayout = new org.jdesktop.layout.GroupLayout(idlenessPanel);
        idlenessPanel.setLayout(lanPanelLayout);
        lanPanelLayout.setHorizontalGroup(
            lanPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(lanPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(lanPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                	.add(enableIdlenessCheckBox)
                	.add(idlenessTimeoutLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                	.add(idlenessTimeoutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 61, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                )
        );
        lanPanelLayout.setVerticalGroup(
            lanPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(lanPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(enableIdlenessCheckBox)
                .add(lanPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(idlenessTimeoutLabel)
                    .add(idlenessTimeoutSpinner, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        keySettingsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Keys Settings"));

        peerPublicKeyLabel.setText("Peer Public Key:");
        
        peerPubKeyTextArea.setLineWrap(true);
        
        loadButton.setText("load");
        
        
        loadButton.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				openFileChooser(e);				
			}
        	
        });
        
        peerPubKeyTextArea.setColumns(20);
        peerPubKeyTextArea.setRows(5);
        jScrollPane1.setViewportView(peerPubKeyTextArea);

        
        org.jdesktop.layout.GroupLayout laayout = new org.jdesktop.layout.GroupLayout(keySettingsPanel);
        keySettingsPanel.setLayout(laayout);
        laayout.setHorizontalGroup(
            laayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, laayout.createSequentialGroup()
                .addContainerGap()
                .add(laayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 388, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, peerPublicKeyLabel)
                    .add(laayout.createSequentialGroup()
                        .add(loadButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(6, 6, 6)))
                .addContainerGap())
        );
        laayout.setVerticalGroup(
            laayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(laayout.createSequentialGroup()
                .addContainerGap()
                .add(peerPublicKeyLabel)
                .add(8, 8, 8)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(laayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(loadButton))
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, keySettingsPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, idlenessPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, rootPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(rootPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(idlenessPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(keySettingsPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        
    }// </editor-fold>//GEN-END:initComponents
    
    /**
     * Opens a FileChooser that permites define the peer public key.
     * @param e The event that represents the clicking of the loadButton.
     */
    protected void openFileChooser(ActionEvent e) {
    	OurGridFileChooser fileChooser = new OurGridFileChooser("Properties file", "properties");
    	File propertiesFile = fileChooser.getFile();
    	
    	if (propertiesFile != null) {
    		Properties prop = CommonUtils.loadProperties(propertiesFile);
    		peerPubKeyTextArea.setText(prop.getProperty(SignatureProperties.PROP_PUBLIC_KEY));
    		 
    	}
    }


	// Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField playpenRootField;
    private javax.swing.JLabel idlenessTimeoutLabel;
    private javax.swing.JSpinner idlenessTimeoutSpinner;
    private javax.swing.JPanel idlenessPanel;
    private javax.swing.JLabel playpenRootLabel;
    private javax.swing.JLabel storageRootLabel;
    private javax.swing.JTextField storageRootField;
    private javax.swing.JPanel rootPanel;
    private javax.swing.JCheckBox enableIdlenessCheckBox;
    private javax.swing.JPanel keySettingsPanel;
    private javax.swing.JLabel peerPublicKeyLabel;
    private javax.swing.JButton loadButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea peerPubKeyTextArea;
    // End of variables declaration//GEN-END:variables

    /**
	 * Initializes the textFields.
	 */
	public void initFields() throws IOException {
		
		WorkerAsyncUIModel model = WorkerAsyncInitializer.getInstance().getModel();
		playpenRootField.setText(model.getProperty(WorkerConfiguration.PROP_PLAYPEN_ROOT));
		storageRootField.setText(model.getProperty(WorkerConfiguration.PROP_STORAGE_DIR));
		
		String idlenessDetector = model.getProperty(WorkerConfiguration.PROP_IDLENESS_DETECTOR);
		if (idlenessDetector != null) {
			enableIdlenessCheckBox.setSelected(idlenessDetector.equals("yes"));
		}
		
		String idlenessTime = model.getProperty(WorkerConfiguration.PROP_IDLENESS_TIME);
		if (idlenessTime != null) {
			idlenessTimeoutSpinner.setValue(Integer.parseInt(
	    			idlenessTime));
		}
		
		peerPubKeyTextArea.setText(model.getProperty(WorkerConfiguration.PROP_PEER_PUBLIC_KEY));
	}


	/**
	 * Save the values of the field inputs.
	 */
	public void saveFieldInputs() throws IOException {
		
		
		/*controller.setProperty(WorkerConfiguration.PROP_PLAYPEN_ROOT, playpenRootField.getText());
		controller.setProperty(WorkerConfiguration.PROP_STORAGE_DIR, storageRootField.getText());
		controller.setProperty(WorkerConfiguration.PROP_PEER_PUBLIC_KEY, peerPubKeyTextArea.getText());
		controller.setProperty(WorkerConfiguration.PROP_IDLENESS_TIME, String.valueOf(
				idlenessTimeoutSpinner.getValue()));
		controller.setProperty(WorkerConfiguration.PROP_IDLENESS_DETECTOR, 
				enableIdlenessCheckBox.isSelected() ? "yes" : "no");*/
		
		WorkerAsyncUIModel model = WorkerAsyncInitializer.getInstance().getModel();
		
		model.setProperty(WorkerConfiguration.PROP_PLAYPEN_ROOT, playpenRootField.getText());
		model.setProperty(WorkerConfiguration.PROP_STORAGE_DIR, storageRootField.getText());
		model.setProperty(WorkerConfiguration.PROP_PEER_PUBLIC_KEY, peerPubKeyTextArea.getText());
		model.setProperty(WorkerConfiguration.PROP_IDLENESS_TIME, String.valueOf(
				idlenessTimeoutSpinner.getValue()));
		model.setProperty(WorkerConfiguration.PROP_IDLENESS_DETECTOR, 
				enableIdlenessCheckBox.isSelected() ? "yes" : "no");
		
		model.workerStopped();
	}

	/**
	 * Disable the editable components of this panel.
	 */
	public void disableInput() {
		playpenRootField.setEnabled(false);
		idlenessTimeoutSpinner.setEnabled(false);
		storageRootField.setEnabled(false);
		enableIdlenessCheckBox.setEnabled(false);
		peerPubKeyTextArea.setEnabled(false);
		loadButton.setEnabled(false);		
	}

	/**
	 * Enable the editable components of this panel.
	 */
	public void enableInput() {
		playpenRootField.setEnabled(true);
		idlenessTimeoutSpinner.setEnabled(true);
		storageRootField.setEnabled(true);
		enableIdlenessCheckBox.setEnabled(true);
		peerPubKeyTextArea.setEnabled(true);
		loadButton.setEnabled(true);		
	}

}
